<script type="text/javascript">
function EventAlbumShowController(albumId, singleShoppingCartPostingUrl,singleShoppingCartRemovalPostingUrl, eventName, albumName, albumDescription) {
	
	var noPhotosAvailable = jQuery('#noPhotosAvailable');
	var selectedPhotosContainer = jQuery('#gallery');
	var imagePreviewContainer = jQuery('#preview-image');
	var coverPhotoImage = jQuery('#coverPhotoImage');	
	
	var UNSELECTED_PREFIX = "Unselected";
	var SELECTED_PREFIX = "Selected";
	
	var CART_SELECTED= "cartSelectedImageBackground";
	var CART_SELECTED_CLASS =  '.'+CART_SELECTED;
	
	var CART_NOT_SELECTED = "cartImageBackground";
	var CART_NOT_SELECTED_CLASS = '.'+CART_NOT_SELECTED;

	var GRID_ELEMENT = "gridElement";
	var GRID_ELEMENT_CLASS = '.'+GRID_ELEMENT;
	
	var shoppingCartPostingUrl = singleShoppingCartPostingUrl;
	var shoppingCartRemovalPostingUrl = singleShoppingCartRemovalPostingUrl;
	
	var albumEntity = new Album(albumId, albumName, albumDescription);
	var _eventName = eventName;
	
	this.loadSelectedPhotos = loadSelectedPhotos;		
	this.addToShoppingCartFromModal = addToShoppingCartFromModal;
	this.addAllToShoppingCart = addAllToShoppingCart;	
	this.getSelectedIdFirstImage=getSelectedIdFirstImage;
	
	function loadSelectedPhotos(photosJSONList){
		jQuery.each(photosJSONList, function()  {			
			var elementName = SELECTED_PREFIX+this.photoId;			
			var photoEntity = new Photo(this.photoId,this.url,elementName,this.thumbnailUrl,this.thumbnailMediumUrl, this.inCart);
			addPhotoToAlbum(photoEntity);	
		});				
	}
	
	/* La estructura que arma es de la siguiente forma 
	<div id={elementName} class="gridMediumImageContainer span3" >																																			
		<a rel="gallery" href={fotoEntera}>
			<img class="gridMediumImage" src={fotoTamañoMedio} />								
		</a>
		<div class="gridMediumImageBottom albumEditableContainer" >									
		 	<div class="gridMediumImageBottomButton deleteImageBackground" />
		 	<div class="gridMediumImageBottomButton coverImageBackground" />
		</div> 		
	</div>			
	 */
	function addPhotoToAlbum(photoEntity){			
		//Agrego la entidad a la lista de fotos.
		albumEntity.addPhotoToAlbum(photoEntity);		
		
		var container = jQuery('<div id="'+photoEntity.getElementName()+'" class="span3 '+GRID_ELEMENT+'" />');
		
		var aPhotoContainer = jQuery('<div class="gridImage" />');
		var aPhotoContainerFooter = jQuery('<div/>');
		
		var galleryRef = jQuery('<a rel="gallery" href="'+photoEntity.getUrl()+'" />');
		var image = jQuery('<img class="gridMediumImage img-rounded" src="'+photoEntity.getThumbnailMediumUrl()+'" />');
		//Agrego la imagen a la gallery.
		galleryRef.append(image);		
		
		//Agrego los botones al footer
		var cartImageButton = jQuery('<div class=" gridBottomButton cartImageBackground" />');
		var shareFacebookImageButton = jQuery('<div class=" gridBottomButton shareFacebookImageBackground" />');
		// var likeFacebookImageButton = jQuery('<div class="fb-like" data-href="' + photoEntity.getUrl() + '" data-send="false" data-layout="button_count" data-width="450" data-show-faces="false"></div>');
		
		aPhotoContainerFooter.append(cartImageButton);
		aPhotoContainerFooter.append(shareFacebookImageButton);
		// aPhotoContainerFooter.append(likeFacebookImageButton);						
		
		cartImageButton.addClass(photoEntity.isInCart() ? CART_SELECTED : CART_NOT_SELECTED);
		cartImageButton.click(function (event) {	

			setCursorByElement(jQuery(this),"wait");
			var selectedElement = jQuery(this).parent().parent();
			var selectedElementName = selectedElement.prop('id');			
			var selectedPhoto = albumEntity.getPhotoEntityByElementName(selectedElementName);	
			if (photoEntity.isInCart()){									
				removeFromShoppingCart(selectedPhoto,cartImageButton);	
			}
			else {				
				addToShoppingCart(selectedPhoto,cartImageButton);
			}
									
	    });
		
		shareFacebookImageButton.click(function (event) {
			var imageLink =  photoEntity.getUrl()
		
			var obj = {
			          method: 'feed',
			          link: imageLink, 
			          picture: imageLink, 
			          name: _eventName,
			          caption: albumEntity.getName(),
			          description: albumEntity.getDescription()
			        };
			
			        FB.ui(obj);
	    });
		
		aPhotoContainer.append(galleryRef);
		container.append(aPhotoContainer)		
		container.append(aPhotoContainerFooter);
					
		container.appendTo(selectedPhotosContainer);		
	}	 

	function setCursorByElement(elem,cursorStyle) {	
	 	elem.css('cursor',cursorStyle); 
	}		
	
	function addToShoppingCartFromModal(){
		var displayedImage = jQuery(".modal-image").find('img').last();		
		var selectedPhoto = albumEntity.getPhotoEntityByURL(displayedImage.attr('src'));

		//Se establece el estilo del cursor
		//Todo deshardcodear!
		jQuery("#btn_addToShoppingCart").css('cursor',"wait");
		
		if(!selectedPhoto.isInCart()){
			//Recupero tambien el cart image			
			var cartImageButton =   jQuery("#"+selectedPhoto.getElementName()).find(CART_NOT_SELECTED_CLASS);
			addToShoppingCart(selectedPhoto,cartImageButton);
		}		
		else {
			setTimeout(function(){
				jQuery("#btn_addToShoppingCart").css('cursor',"pointer");
			}, 1500);
			
		}
	}
	
	function addToShoppingCart(selectedPhoto,cartImageButton){
		jQuery.ajax({
            url: shoppingCartPostingUrl,
            datatype:"json",
            type: "POST",                        
            data: { "photoId": selectedPhoto.getId() },
            async:true,		                
            success: function(data){

            	//Se analiza si se debe cambiar la imagen del cart en la pantalla superior.        		
            	setCartToolBarVisibility(data.photosStillInCart);	
        		
            	selectedPhoto.setInCart(true);            	
            	cartImageButton.removeClass(CART_NOT_SELECTED);
            	cartImageButton.addClass(CART_SELECTED);            	
            	cartImageButton.css('cursor',"pointer");
            	jQuery("#btn_addToShoppingCart").css('cursor',"pointer");
            },
            error: function(){		                		                				       
            	alert("Failure");		                   
            }	                
        });	
	}
	
	function removeFromShoppingCart(selectedPhoto,cartImageButton){
		jQuery.ajax({
            url: shoppingCartRemovalPostingUrl,
            datatype:"json",
            type: "POST",                        
            data: { "photoId": selectedPhoto.getId() },
            async:true,		                
            success: function(data) {
            	//Se analiza si se debe cambiar la imagen del cart en la pantalla superior.        		
            	setCartToolBarVisibility(data.photosStillInCart);	
            	
            	selectedPhoto.setInCart(false);            	
            	cartImageButton.removeClass(CART_SELECTED);
            	cartImageButton.addClass(CART_NOT_SELECTED);
            	setCursorByElement(cartImageButton,"pointer");
            },
            error: function(){		                		                				       
            	alert("Failure");		                   
            }	                
        });	
	}
	
	function addAllToShoppingCart(postingUrl){
		jQuery.ajax({
            url: postingUrl,
            datatype:"json",
            type: "POST",                        
            data: { "albumId": albumEntity.getId() },
            async:true,		                
            success: function(data) {
            	//Se analiza si se debe cambiar la imagen del cart en la pantalla superior.        		
            	setCartToolBarVisibility(data.photosStillInCart);	
            	
            	albumEntity.addAllToShoppingCart()
            	var cartImages = jQuery(CART_NOT_SELECTED_CLASS);
            	cartImages.removeClass(CART_NOT_SELECTED);
            	cartImages.addClass(CART_SELECTED);
            	
            },
            error: function(){		                		                				       
            	alert("Failure");		                   
            }	                
        });	
	}
		
	function setCartToolBarVisibility(photosInCart){
		jQuery('#cartToolbarIcon').attr('src',photosInCart ? "${resource(dir:'images', file: 'cart_filled_m.png')}"  : "${resource(dir:'images', file: 'cart_m.png')}")
	}

	//devuelve a la primer foto seleccionada.
	function getSelectedIdFirstImage(){
		var firstImage = selectedPhotosContainer.find(GRID_ELEMENT_CLASS).first();		  			
		return firstImage.prop('id');
	}
}
</script>